package com.hrt.datasender.datacollect.drive.text;

import com.btcode.exception.MsgException;
import com.btcode.schedule.ScheduleManager;
import com.hrt.datasender.datacollect.drive.DriveConfigModel;
import com.hrt.datasender.datadao.model.BcDeviceConfigModel;
import com.hrt.datasender.datadao.model.BcDeviceMonitorParamModel;
import com.hrt.datasender.datadao.model.BcDevicesModel;
import com.hrt.datasender.datadao.model.BdSourceModel;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class ZeeiDrive extends TextSerialBaseDrive {

    @Override
    public List<BdSourceModel> processSerialData(byte[] data, HashMap<Integer, String> paramCodeMap,
            DriveConfigModel configs) {
        String msg = new String(data);
        msg = msg.replaceAll("[\u0000]", "");
        msg = msg.trim();
        List<BdSourceModel> sourceModels;
        /**
         * 判断包头包尾
         * Z0,0.292,2020-12-03 14: 0:13,100,00000000000000000000000000000000<ZEEI>
         * 注意：驱动协议编码必须填1
         */
        try{
            log.info("收到数据报文" + msg + "结束");
            if(msg.startsWith("Z0,")&&msg.endsWith("<ZEEI>")){
                String[] arrMsg = msg.split(",");
                String value = arrMsg[1];
                Double dValue = Double.parseDouble(value);

                sourceModels = new ArrayList<>();
                BdSourceModel sourModel = new BdSourceModel();
                String paramCodeBus = paramCodeMap.get(1);
                sourModel.setParamCodeBus(paramCodeBus);
                sourModel.setDatatime(new Date());
                sourModel.setMeasRe(dValue);
                sourceModels.add(sourModel);
                return sourceModels;
            }
            else{
                log.info("数据包不完整，等待下一条数据包");
            }
        }
        catch (Exception e){
            log.info(e);
        }
        return null;
    }

    @Override
    public String getNote() {
        return null;
    }

    @Override
    public String getDriveName() {
        return "中兴协议";
    }

    @Override
    public String getConsStr() {
        return "0/10 * * * * ?";
    }

    @Override
    protected void beforeInit(BcDevicesModel device, List<BcDeviceMonitorParamModel> params,
            List<BcDeviceConfigModel> configs) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void registerAskDataJob(BcDevicesModel device, DriveConfigModel configs) {
        HashMap<String, Object> data = new HashMap<>();

        data.put("device", device);
        data.put("deviceConfigs", configs);
        String consStr = configs.getConfig().get("consStr");

        if (consStr == null || consStr.equals("")) {
            throw new MsgException("请设置数据询问时间间隔");
        }

        String jobName = getClass().getName() + "." + device.getId();

        ScheduleManager.getInstance().addJob(ZeeiDriveAsker.class, consStr, data, jobName);
    }
}